<template>
  <div>
    <div id="map-container" ref="cesiumContainer" class="map" style="width: 100%">
      <!-- 加载提示 -->
      <div v-if="loading" class="loading-overlay">正在加载中，请稍候...</div>

      <!-- 鼠标位置（固定左下角） -->
      <div class="mouse-position">位置： {{ mousePos.x.toFixed(6) }} , {{ mousePos.y.toFixed(6) }}</div>
      <!-- <div class="mouse-position">位置： {{ mousePos.x.toFixed(6) }} , {{ mousePos.y.toFixed(6) }}</div> -->

      <!-- 左上角按钮工具栏 -->
      <div class="toolbar">
        <div class="toolbar-icon" @mouseenter="hoverIcon = 'refresh'" @mouseleave="hoverIcon = ''" @click="onClickRefreshBtn">
          <div class="toolbar-img-bg" :class="{ 'toolbar-img-bg-hover': hoverIcon === 'refresh' }">
            <img
              :src="hoverIcon === 'refresh' ? require('@/assets/images/refresh2.png') : require('@/assets/images/refresh.png')"
              class="toolbar-img"
              :class="{ 'toolbar-img-hover': hoverIcon === 'refresh' }"
              alt="refresh"
            />
          </div>
          <div v-if="hoverIcon === 'refresh'" class="toolbar-label toolbar-label-hover">重置</div>
        </div>
        <!-- <div class="toolbar-icon" @mouseenter="hoverIcon='site'" @mouseleave="hoverIcon=''" @click="onClickSiteIcon">
          <div class="toolbar-img-bg" :class="{ 'toolbar-img-bg-hover': hoverIcon==='site' }">
            <img :src="hoverIcon==='site'?require('@/assets/images/site2.png'):require('@/assets/images/site1.png')" class="toolbar-img" :class="{ 'toolbar-img-hover': hoverIcon==='site' }" alt="site" />
          </div>
          <div v-if="hoverIcon==='site'" class="toolbar-label toolbar-label-hover">监测点</div>
        </div>
        <div class="toolbar-icon" @mouseenter="hoverIcon='shebei'" @mouseleave="hoverIcon=''" @click="onClickShebeiIcon">
          <div class="toolbar-img-bg" :class="{ 'toolbar-img-bg-hover': hoverIcon==='shebei' }">
            <img :src="hoverIcon==='shebei'?require('@/assets/images/shebei2.png'):require('@/assets/images/shebei1.png')" class="toolbar-img" :class="{ 'toolbar-img-hover': hoverIcon==='shebei' }" alt="shebei" />
          </div>
          <div v-if="hoverIcon==='shebei'" class="toolbar-label toolbar-label-hover">设备</div>
        </div> -->
        <el-select v-model="inputRadarName" placeholder="查询" @change="onChangeEvent">
          <el-option v-for="item in radarNames" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <!-- 雷达信息弹窗-->
      <RadarItemDialog :visible.sync="openRadarItemDialog" :radar-info="clickRadarRow" />
      <!-- 监控点信息弹窗-->
      <RadarPointDetailDialog v-if="openRedarPointDetailDialog" :visible.sync="openRedarPointDetailDialog" :radar-info="radarRow" :radar-point-info="clickRadarPointRow" />
    </div>
  </div>
</template>

<script>
import { getAllRadarList, getRadarPointList } from "@/api/radar/radar-point";
import { getRadarList } from "@/api/radar/sys-radar";
import { RadarPointTag, RadarTag, TCesiem } from "@/utils/tcesium/tcesium";
import RadarPointDetailDialog from "../radar/radar-point/RadarPointDetailDialog.vue";
import RadarItemDialog from "../radar/sys-radar/RadarItemDialog.vue";

// 引用public下面的Cesium.js
const Cesium = window["Cesium"];

export default {
  name: "Dashboard",
  components: {
    RadarPointDetailDialog,
    RadarItemDialog
  },
  data() {
    return {
      // 事件
      handler: null,
      loading: true,
      // 雷达列表
      radarList: [],
      // 选中的雷达
      radarRow: null,
      // 点击的雷达
      clickRadarRow: null,
      // 点击的雷达点位
      clickRadarPointRow: null,
      radarNames: [],
      inputRadarName: "",
      viewer: null,
      // 雷达和监测点列表相关数据
      pointList: [],
      // 鼠标位置
      mousePos: {
        x: 0, // 经度
        y: 0 // 纬度
      },
      openRadarItemDialog: false, // 控制雷达信息弹出框显示
      showRadarAlarmDialog: false, // 控制雷达报警信息弹窗
      openRedarPointDetailDialog: false, // 控制雷达点位弹出框显示
      hoverIcon: "", // 工具栏悬停图标
      radarAllList: [],
      pointAllList: []
    };
  },
  computed: {},

  // 页面创建时触发
  async created() {
    console.log("Dashboard页面创建时触发");
    this.init();
  },
  // 页面加载完成时触发
  mounted() {
    console.log("Dashboard页面加载完成时触发");
  },
  // 页面再次激活时
  activated() {
    console.error("Dashboard 页面再次激活时");
    // this.init();
  },
  // 页面隐藏时
  deactivated() {},

  beforeDestroy() {
    // 组件销毁前彻底停止轮询
    console.log("RadarStateInfo beforeDestroy");
    this.viewDestroy();
  },
  // 离开页面时触发
  destroyed() {
    console.log("RadarStateInfo destroyed");
    this.viewDestroy();
  },

  methods: {
    // 初始化地图信息
    async init() {
      this.loading = true;
      console.log("初始化地图信息");
      // 获取雷达列表
      let resp = await getRadarList({ pageIndex: 1, pageSize: 100 });
      let { list } = resp.data;
      console.log("雷达列表：", list);
      this.radarList = list;
      if (!list || list.length === 0) {
        this.loading = false;
        console.error("没有雷达，暂时不显示地图信息！！！");
        return;
      }

      let { lng, lat, radarId } = list[0];
      let pos = { x: lng, y: lat };

      try {
        // 创建 Cesium viewer
        this.viewer = await TCesiem.NewTCesium(this.$refs.cesiumContainer, pos);
        this.loading = false;

        // 绑定鼠标事件，保证在 viewer 初始化后执行
        this.onCesiumEventHandler();

        // 初始化下拉框
        this.initRadarNames(list);

        // 显示雷达点位
        // await this.showRadarEntities(radarId);

        // 添加窗口大小变化事件监听器
        window.addEventListener("resize", this.handleResize);
        await this.getAllData();
        this.getAllSiteRadar();
      } catch (err) {
        console.error("初始化Cesium失败:", err);
      }
    },
    // 销毁 viewer 和事件监听器
    viewDestroy() {
      console.log("销毁 Cesium 实例及事件监听器");
      if (this.handler && !this.handler.isDestroyed()) {
        this.handler.destroy();
        this.handler = null;
      }
      if (this.viewer && !this.viewer.isDestroyed()) {
        this.viewer.entities.removeAll();
        this.viewer.destroy();
        this.viewer = null;
      }

      // 移除窗口大小监听
      window.removeEventListener("resize", this.handleResize);
    },

    // 窗口大小变化回调
    handleResize() {
      if (this.viewer) {
        this.viewer.resize();
      }
    },

    // 监听鼠标事件
    onCesiumEventHandler() {
      if (!this.viewer) return;

      try {
        this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

        // 鼠标移动事件
        TCesiem.OnMouseMoveEvent(this.viewer, this.handler, position => {
          this.mousePos = position;
        });

        // 鼠标左键点击事件
        TCesiem.OnMouseLifeClickEvent(this.viewer, this.handler, 1, callback => {
          console.log("点击实物:", callback);
          let { id, tag, pos } = callback;

          TCesiem.FlyToPos(this.viewer, 0.5, pos, () => {
            if (tag === RadarTag) {
              this.clickRadarRow = this.radarAllList.find(item => item.radarKey === id);
              this.openRadarItemDialog = true;
            }
            if (tag === RadarPointTag) {
              const [radarId, radarPointId] = id.split("-");
              this.radarRow = this.radarAllList.find(item => item.radarId == radarId);
              this.clickRadarPointRow = this.pointAllList.find(item => item.id == radarPointId);
              this.openRedarPointDetailDialog = true;
            }
          });
        });
      } catch (error) {
        console.error("绑定鼠标事件失败:", error);
      }
    },

    // 显示雷达点位
    async showRadarEntities(radarId) {
      // 先清空所有实体
      this.viewer.entities.removeAll();

      let radarItem = this.radarList.find(item => item.radarId === radarId);
      this.radarRow = radarItem;
      let { lng, lat, radarKey, radarName } = radarItem;
      let pos = { x: lng, y: lat };
      // 添加雷达
      TCesiem.AddRadarEntities(this.viewer, pos, radarKey, radarName);
      // 飞到指定位置
      TCesiem.FlyToPos(this.viewer, 2, pos, () => {});

      // 添加雷达点位
      let resp = await getRadarPointList({ radarId });
      let radarPointList = resp.data.list;
      this.radarPointList = radarPointList;
      console.log("点位列表：", radarPointList);
      if (!this.viewer || radarPointList.length == 0 || radarPointList[0].radarId != radarId) return;
      for (const item of radarPointList) {
        let { lng, lat, id: radarPointId, radarId, pointName } = item;
        let pos = { x: lng, y: lat };
        TCesiem.AddRadarPointEntities(this.viewer, pos, radarPointId, radarId, pointName);
      }
    },

    // resizeCanvas() {
    //   this.viewer.canvas.style.width = "100%";
    //   this.viewer.canvas.style.height = "100vh";
    //   this.viewer.resize(); // 确保调用 resize 方法来更新视图大小
    // },

    // 初始化雷达下拉框
    initRadarNames(radarList) {
      this.radarNames = [{ value: "", label: "全部" }];
      for (const item of radarList) {
        let { radarName, radarId } = item;
        this.radarNames.push({ value: radarId, label: radarName });
      }
      this.inputRadarName = "";
    },
    async getAllData() {
      let resp = await getAllRadarList();
      this.radarAllList = resp.data.radarList;
      this.pointAllList = resp.data.radarPointList;
      // console.log("所有雷达：", this.radarAllList);
      //  console.log("所有点：", this.pointAllList);
      //
    },
    async getAllSiteRadar() {
      console.log("展示所有雷达和监测点数据");
      // 展示所有雷达和监测点数据
      if (this.viewer) {
        // 先清空所有实体
        this.viewer.entities.removeAll();
      }
      console.log("this.viewer", this.viewer);
      // 展示所有雷达
      this.radarAllList.forEach(item => {
        let pos = { x: item.lng, y: item.lat };
        TCesiem.AddRadarEntities(this.viewer, pos, item.radarKey, item.radarName);
      });
      // 展示所有监测点
      if (this.pointAllList.length > 0) {
        this.pointAllList.forEach(point => {
          let pos = { x: point.lng, y: point.lat };
          TCesiem.AddRadarPointEntities(this.viewer, pos, point.id, point.radarId, point.pointName);
        });
      }
    },
    // 点击刷新按钮
    async onClickRefreshBtn() {
      console.log("点击刷新按钮");
      // this.viewDestroy();
      // await this.init();
      // console.log("this.viewer", this.viewer);
      this.getAllSiteRadar();
    },
    // 下拉框change
    onChangeEvent(value) {
      if (!value) {
        this.getAllSiteRadar();
      } else {
        this.showRadarEntities(value);
      }
    },
    // 点击监测点图标
    async onClickSiteIcon() {
      if (this.viewer) {
        this.viewer.entities.removeAll();
        this.viewer.scene.primitives.removeAll();
      }
      if (this.radarPointList && this.radarPointList.length > 0) {
        // 飞行到第一个点位
        const first = this.radarPointList[0];
        if (first) {
          // 先只添加第一个点的图标
          TCesiem.AddRadarPointEntities(this.viewer, { x: first.lng, y: first.lat }, first.id, first.radarId, first.pointName);
          TCesiem.FlyToPos(this.viewer, 1.2, { x: first.lng, y: first.lat }, () => {
            // 飞行结束后再批量添加所有点
            this.radarPointList.forEach(item => {
              if (item.id !== first.id) {
                let { lng, lat, id: radarPointId, radarId, pointName } = item;
                let pos = { x: lng, y: lat };
                TCesiem.AddRadarPointEntities(this.viewer, pos, radarPointId, radarId, pointName);
              }
            });
          });
        }
      }
    },
    // 点击设备图标
    async onClickShebeiIcon() {
      if (this.viewer) {
        this.viewer.entities.removeAll();
        this.viewer.scene.primitives.removeAll();
      }
      if (this.radarList && this.radarList.length > 0) {
        // 飞行到第一个设备
        const first = this.radarList[0];
        if (first) {
          // 先只添加第一个设备的图标
          TCesiem.AddRadarEntities(this.viewer, { x: first.lng, y: first.lat }, first.radarKey, first.radarName);
          TCesiem.FlyToPos(this.viewer, 1.2, { x: first.lng, y: first.lat }, () => {
            // 飞行结束后再批量添加所有设备
            this.radarList.forEach(item => {
              if (item.radarKey !== first.radarKey) {
                let { lng, lat, radarKey, radarName } = item;
                let pos = { x: lng, y: lat };
                TCesiem.AddRadarEntities(this.viewer, pos, radarKey, radarName);
              }
            });
          });
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.map {
  position: relative; /* 父容器要相对定位，子元素才能绝对定位 */
  width: 100%;
  // height: 100vh;
  height: calc(100vh - 93px);
}

/* 左上角工具栏 */
.toolbar-img-bg {
  background: #fff;
  border-radius: 50%;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: box-shadow 0.2s;
}
.toolbar-img-bg-hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
}
.toolbar {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 999;
  display: flex;
  gap: 18px;
  align-items: flex-end;
}
.toolbar-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: background 0.2s;
}
.toolbar-img {
  width: 32px;
  height: 32px;
  transition: transform 0.2s cubic-bezier(0.4, 2, 0.3, 1);
}
.toolbar-img-hover {
  transform: scale(1.25);
  /* 保持居中不位移 */
  margin: 0;
}
.toolbar-label {
  display: none;
}
.toolbar-label-hover {
  display: block;
  // margin-top: 6px;
  font-size: 13px;
  color: #fff;
  text-align: center;
  letter-spacing: 1px;
  font-weight: 500;
  background: #222;
  border-radius: 12px;
  padding: 2px 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
  position: absolute;
  top: 50px;
  white-space: nowrap;
}
.toolbar-label-hover::before {
  content: "";
  position: absolute;
  top: -8px;
  left: 50%;
  transform: translateX(-50%);
  border-width: 0 8px 8px 8px;
  border-style: solid;
  border-color: transparent transparent #222 transparent;
  width: 0;
  height: 0;
  z-index: 2;
}
/* 左下角鼠标位置 */
.mouse-position {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 999;
}
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.5);
}
</style>
